package cn.echo.hrm.controller;

import cn.echo.hrm.dto.TenantEnteringDto;
import cn.echo.hrm.exception.BusinessException;
import cn.echo.hrm.service.ITenantService;
import cn.echo.hrm.domain.Tenant;
import cn.echo.hrm.query.TenantQuery;
import cn.echo.hrm.util.AjaxResult;
import cn.echo.hrm.util.PageList;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 服务接口controller
 * @author lxy
 * @since 2022-04-06
 */
@RestController
@RequestMapping("/tenant")
public class TenantController {
    @Autowired
    public ITenantService tenantService;


    /**
     * 保存和修改公用的
     *
     * @param tenant 传递的实体
     * @return Ajaxresult转换结果
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Tenant tenant) {
        try {
            if (tenant.getId() != null)
                tenantService.updateById(tenant);
            else
                tenantService.insert(tenant);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("保存对象失败！" + e.getMessage());
        }
    }

    /**
     * 删除对象信息
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/{id}")
    public AjaxResult delete(@PathVariable("id") Long id) {
        try {
            tenantService.deleteById(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("删除对象失败！" + e.getMessage());
        }
    }

    //获取用户
    @GetMapping("/{id}")
    public Tenant get(@PathVariable("id") Long id) {
        return tenantService.selectById(id);
    }


    /**
     * 查看所有的员工信息
     *
     * @return
     */
    @GetMapping
    public List<Tenant> list() {

        return tenantService.selectList(null);
    }


    /**
     * 分页查询数据
     *
     * @param query 查询对象
     * @return PageList 分页对象
     */
    @PostMapping("/list")
    public PageList<Tenant> json(@RequestBody TenantQuery query) {
        Page<Tenant> page = new Page<Tenant>(query.getPage(), query.getRows());
        return tenantService.selectPageList(page, query);
    }

    //机构入驻
    @PostMapping("/entering")
    //@Valid 识别jsr303校验
    public AjaxResult entering(@RequestBody @Valid TenantEnteringDto enteringDto) {
//        try {
            tenantService.entering(enteringDto);
            return AjaxResult.me();
//        } catch (BusinessException b) {//系统异常
//            b.printStackTrace();
//            return AjaxResult.me().setSuccess(false).setMessage(b.getMessage());
//
//        } catch (Exception e) { //非系统异常
//            e.printStackTrace();
//            return AjaxResult.me().setSuccess(false).setMessage("系统错误");
//        }
    }
}

